import { useCallback } from 'react';
import { useInbizRouter } from '@inbiz/hooks';
import { useSearchResultPage } from './useSearchResultPage';
import { useSearchUIState } from './useSearchUIState';
import { useConfigEventsApi, useSearchPropsState } from './useSearchPropsState';
import { useSearchUIDispatch } from './useSearchUIDispatch';
import { routerPrefix } from 'InbizConfig';
import { useInbiz } from './useInbiz';
export type ISearchResultData = {
  IndexName: ['_document_'] | ['_all_'] | string[]; // _document_ 文档类型，_all_ 所有, 其他字符串为IndexName
  documentType?: 'file' | 'folder'; //  'IndexName'  为_document_时有效
  SearchFields?: {
    IndexFieldName: 'filecontent' | 'filename' | 'filetag' | 'foldername';
  }[]; // 'IndexName'  为_document_时有效
  FuzzyFields?: {
    IndexFieldName: 'filecontent' | 'filename' | 'filetag' | 'foldername';
  }[];
  KeyWord?: string; //搜索关键字
  KeyWords?: string[]; //搜索关键字数组
  SearchWhere?: string; // 高级过滤条件
  isFuzzySearch: boolean; // 精准、模糊搜索
  isAdvanced: boolean; // 是否为高级搜索
  ModuleName?: string; //搜索的模块id
  ImgMarkId?: string; //以图搜图文件Mark Id
  Graph?: boolean; //是否开启关键字图谱
  SecondaryWord?: string; //结果中搜索
  IsSynonymSearch: boolean,
};

export enum ecmSearchTypeField {
  filecontent = 1,
  filename,
  filetag,
  foldername,
}
export const useJumpResult = (onChange?: (key: string) => void) => {
  const history = useInbizRouter();

  const state = useSearchUIState();
  const searchResultPage = useSearchResultPage();
  const props = useSearchPropsState() as unknown as {
    emit: (key: string, target: string, data: object) => void;
    controlId: string,
    synonymSearch: boolean,
  };
  const { configEvents } = useConfigEventsApi();
  const updateState = useSearchUIDispatch();
  const inbiz: any = useInbiz();
  // searchData 为string时为普通搜索，object时为高级搜索
  return useCallback(
    async (
      searchData:
        | string
        | {
          data?: {
            inbiz?: () => void;
            IndexName?: [string];
            SearchWhere: string;
            rawSearchWhere: object;
          };
          dmsType?: 'file' | 'folder';
          metaData?: any;
          parentFolderLevel?: number,
          parentFolderPath?: string,
          parentTopFolderId?: string,
          parentFolderid: string
        },
      keywords?: string[],
      imgMark?: string,
      searchMeta?: {
        isResultButton: boolean | undefined; // 是否是结果中检索
        currentValue: string; // 当前输入框的值
        customFolderId: string, // 文件夹id
      },
    ) => {
      const { ecmSearchType, isFuzzySearch, searchFolder } = state;
      const { isAll, isDMS, indexLibraries, selectFolderID, guid, keywordAtlas, isFile, isFolder } =
        state.selectShowTab!;
      const isAdvanced = typeof searchData !== 'string';
      // 文档搜索字段， 只在普通搜索时生效
      const SearchFields = [];
      if ((isDMS || isFile || isFolder) && ecmSearchType) {
        SearchFields.push(
          ...ecmSearchType.map((item) => ({ IndexFieldName: ecmSearchTypeField[item] })),
        );
      }
      // 搜索的索引库
      const IndexName = [];

      // 过滤条件
      let SearchWhere = '';
      // dms普通搜索时， 或者为高级搜索时添加
      if (isAdvanced) {
        // 高级搜索中存在tabs时，搜索tabs激活的tab
        if (searchData?.data?.IndexName) {
          IndexName.push(...searchData.data?.IndexName);
        } else {
          if (isDMS) {
            IndexName.push('_document_');
          } else {
            IndexName.push(...(indexLibraries?.map((item) => item.IndexName) || []));
          }
        }
        SearchWhere += searchData.data?.SearchWhere || '';
      } else {
        IndexName.push(
          ...(isAll
            ? ['_all_']
            : isDMS
              ? ['_document_']
              : indexLibraries?.map((item) => item.IndexName) || []),
        );
        if (isDMS) {
          const key = ecmSearchType?.includes(4) ? 'folder' : 'file';
          let folderid =
            searchFolder == 'curfolder'
              ? selectFolderID?.[0]?.parentfolderid == 2
                ? inbiz.userInfo.topPersonalFolderId
                : selectFolderID?.[0]?.folderid
              : '';
          if (searchMeta?.customFolderId) {
            if (key == 'folder') {
              SearchWhere += `(folderpath:(${searchMeta.customFolderId}) OR masterfolderpathpath:(${searchMeta.customFolderId}))`;
            } else {
              SearchWhere += `(filepath:(${searchMeta.customFolderId}) OR masterfilepath:(${searchMeta.customFolderId}))`;
            }
          } else if (folderid) {
            SearchWhere += `${key}path:(${folderid})`;
          }
        } else if (searchMeta?.customFolderId) {
          if (IndexName.includes('file')) {
            SearchWhere += `(filepath:(${searchMeta.customFolderId}) OR masterfilepath:(${searchMeta.customFolderId}))`;
          } else if (IndexName.includes('folder')) {
            SearchWhere += `(folderpath:(${searchMeta.customFolderId}) OR masterfolderpath:(${searchMeta.customFolderId}))`;
          }

        }
      }
      // 搜索入口缓存参数
      const searchEngineData = {
        IndexName: IndexName,
        documentType: isDMS
          ? isAdvanced
            ? searchData.dmsType
            : ecmSearchType?.includes(4)
              ? 'folder'
              : 'file'
          : undefined,
        isFuzzySearch,
        SearchFields: !isAdvanced && isFuzzySearch ? SearchFields : [], // 高级搜索和精确搜索不传
        FuzzyFields: isFuzzySearch || isAdvanced ? [] : SearchFields, // 高级搜索和模糊搜索不传
        SearchWhere,
        isAdvanced,
        KeyWord: !isAdvanced ? searchData : '',
        KeyWords: keywords || [],
        ModuleName: guid,
        ImgMarkId: imgMark,
        Graph: keywordAtlas || false,
        searchMeta,
        IsSynonymSearch: props.synonymSearch,
        selectShowTab: { ...state.selectShowTab, save: true },
        searchFolder: state.searchFolder,
        ecmSearchType: state.ecmSearchType,
        keyword: !isAdvanced ? searchData : '',
        keywords: keywords || [],
        metaData: searchData?.metaData,
        parentFolderLevel: searchData?.parentFolderLevel,
        parentFolderPath: searchData?.parentFolderPath,
        parentTopFolderId: searchData?.parentTopFolderId,
        parentFolderid: searchData?.parentFolderid
      };
      if (typeof searchData === 'string') {
        onChange?.(searchData);
      }
      // 搜索前调用扩展方法
      const searchResultData =
        (await configEvents.current.onBeforeSearch?.(
          { ...searchEngineData } as any,
          searchData,
        )) ?? searchEngineData;
      if (searchResultData === false) {
        return;
      }


      // if (searchData?.metaData) {
      //   localStorage.setItem(
      //     props.controlId,
      //     JSON.stringify(searchData?.metaData),
      //   );
      // }
      localStorage.removeItem('_searchEngineStatus')
      sessionStorage.removeItem('_searchEngineStatus')
      localStorage.setItem(
        '_searchEngineStatus',
        JSON.stringify(searchResultData),
      );
      if (searchResultPage.searchResultType == 'page') {
        if (searchResultPage.searchResultPage) {
          const resultPages = searchResultPage.searchResultPage.split(',')
          const pageId = resultPages[0];
          const url = `${location.pathname}${location.search}#${routerPrefix}${pageId}`;
          const newUrl =
            (await configEvents.current.onBeforeOpenPage?.(url, searchResultData)) || url;
          if (searchResultPage.searchResultPageType === '_blank') {
            // if (searchData) {
            window.open(newUrl);
            // }
          } else {
            const resultComponentId = pageId.split('/')[1]

            if (history.location.pathname == `${routerPrefix}${resultPages[0]}` || resultComponentId === inbiz.pageId) {
              if (window.inbizGlobal(resultComponentId).page) {
                // 绑定类型为页面时, 没有搜索结果组件的id, 所以查找整个页面的搜索结果组件来获取搜索结果组件的id
                const allPages = window.inbizGlobal(resultComponentId).page.getFields()
                const searchResultPage = allPages.find(item => item && item.componentType == 'SearchResultEngine') || {}
                const searchResultId = searchResultPage?.componentProps.controlId
                if (searchResultId) {
                  props.emit?.('onSearch', searchResultId, searchResultData);
                }
              }
            } else {
              history.push(`${routerPrefix}${pageId}`);
            }
          }
        }
      } else {
        props.emit?.('onSearch', searchResultPage.searchResultComponent, searchResultData);
      }
      updateState({ visibleDrawer: false, switchAdSearch: false });
    },
    [onChange, searchResultPage, state, props.emit, updateState],
  );
};
